package com.sky.service.impl;

import com.sky.entity.Orders;
import com.sky.mapper.DishMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.WorkSpaceService;
import com.sky.vo.BusinessDataVO;
import com.sky.vo.DishOverViewVO;
import com.sky.vo.OrderOverViewVO;
import com.sky.vo.SetmealOverViewVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Service
public class WorkSpaceServiceImpl implements WorkSpaceService {
    @Autowired
    DishMapper dishMapper;

    @Autowired
    private SetmealMapper setmealMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    /**
     * 查询菜品总览
     *
     * @return
     */
    @Override
    public DishOverViewVO getOverviewDishes() {
        // 启售数量
        Integer sold = dishMapper.queryStatusNum(1L);
        // 已停售数量
        Integer discontinued = dishMapper.queryStatusNum(2L);
        return DishOverViewVO.builder()
                .sold(sold)
                .discontinued(discontinued)
                .build();
    }

    /**
     * 查询今日运营数据
     * @param now
     * @return
     * @throws ExecutionException
     * @throws InterruptedException
     */
    @Override
    public BusinessDataVO getBusinessData(LocalDate now) throws ExecutionException, InterruptedException {
        ExecutorService executorService = Executors.newFixedThreadPool(10);

        CompletableFuture<BigDecimal> turnoverFuture = CompletableFuture.supplyAsync(() -> {
            // 计算营业额
            return orderMapper.sumByCondition(Orders.COMPLETED, now);
        }, executorService);

        CompletableFuture<Integer> totalOrderFuture = CompletableFuture.supplyAsync(() -> {
            // 计算总订单数量
            HashMap<Object, Object> params = new HashMap<>();
            params.put("date", now);
            return orderMapper.countByMap(params);
        }, executorService);

        CompletableFuture<Integer> validOrderCountFuture = CompletableFuture.supplyAsync(() -> {
            // 计算有效订单数量
            HashMap<Object, Object> params = new HashMap<>();
            params.put("date", now);
            params.put("status", Orders.COMPLETED);
            return orderMapper.countByMap(params);
        }, executorService);

        CompletableFuture<Integer> newUsersFuture = CompletableFuture.supplyAsync(() -> {
            // 计算新增用户数
            HashMap<Object, Object> params = new HashMap<>();
            params.put("newUserDate", LocalDateTime.now());
            return userMapper.countByMap(params);
        }, executorService);

        // 等待所有任务完成
        CompletableFuture<Void> allFutures = CompletableFuture.allOf(turnoverFuture, totalOrderFuture, validOrderCountFuture, newUsersFuture);
        allFutures.get(); // 等待所有任务完成

        BigDecimal turnover = turnoverFuture.get();
        Integer totalOrder = totalOrderFuture.get();
        Integer validOrderCount = validOrderCountFuture.get();
        Integer newUsers = newUsersFuture.get();

        // 计算订单完成率和均客单价
        double orderCompletionRate = 0.0;
        double unitPrice = 0.0;
        if (validOrderCount != null && totalOrder != null && turnover != null && totalOrder != 0 && validOrderCount != 0) {
            orderCompletionRate = (double) validOrderCount / totalOrder;
            unitPrice = turnover.doubleValue() / validOrderCount;
            unitPrice = Double.parseDouble(String.format("%.2f", unitPrice));
        }

        // 构建返回结果
        return BusinessDataVO.builder()
                .newUsers(newUsers)
                .orderCompletionRate(orderCompletionRate)
                .turnover(turnover)
                .unitPrice(unitPrice)
                .validOrderCount(validOrderCount)
                .build();
    }


    /**
     * 查询订单管理数据
     *
     * @param now
     * @return
     */
    @Override
    public OrderOverViewVO overviewOrders(LocalDate now) {
        HashMap<Object, Object> param = new HashMap<>();
        param.put("date", now);
        // 全部订单
        Integer allOrders = orderMapper.countByMap(param);

        //待接单数量
        param.put("status", Orders.TO_BE_CONFIRMED);
        Integer waitingorders = orderMapper.countByMap(param);

        //待派送数量
        param.put("status", Orders.CONFIRMED);
        Integer deliveredorders = orderMapper.countByMap(param);

        //已完成数量
        param.put("status", Orders.COMPLETED);
        Integer completedorders = orderMapper.countByMap(param);

        // 已取消数量
        param.put("status", Orders.CANCELLED);
        Integer cancelledorder = orderMapper.countByMap(param);

        return OrderOverViewVO.builder()
                .allOrders(allOrders)
                .cancelledOrders(cancelledorder)
                .completedOrders(completedorders)
                .deliveredOrders(deliveredorders)
                .waitingOrders(waitingorders)
                .build();
    }

    /**
     * 查询套餐总览
     *
     * @return
     */
    @Override
    public SetmealOverViewVO overviewSetmeals() {
        Integer sold = setmealMapper.countStatus(1);
        Integer discontinued = setmealMapper.countStatus(0);
        return SetmealOverViewVO.builder()
                .sold(sold)
                .discontinued(discontinued)
                .build();
    }
}
